<?php

/**
 * 短信
 * File Name：MembersMsgModel.php
 * File Encoding：UTF-8
 * File New Time：2014-8-14 14:42:44
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class MembersMsgModel extends BaseModel {

    public function tableName() {
        return '{{members_msg}}';
    }

    public function rules() {
        return array(
            array('senduid', 'required', 'message' => '发送者uid！'),
            array('sendname', 'required', 'message' => '发送者用户名！'),
            array('recuid', 'required', 'message' => '接收者uid！'),
            array('recuname', 'required', 'message' => '接收者用户名！'),
            array('userid', 'required', 'message' => '用户ID不能为空！'),
            //安全免验证的
            array('is_read,answerid,suid,ruid,msgid,datetime', 'safe'),
        );
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            //改变数据
            $this->datetime = time();
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 设置短信状态
     * @param type $id
     * @param type $status
     * @return boolean
     */
    public function setRead($userid, $ids, $status = 1) {
        if (empty($ids) || empty($userid)) {
            return false;
        }
        $msgid = $this->findAll($this->where(array('id' => array('IN', $ids))));
        if (empty($msgid)) {
            return true;
        }
        foreach ($msgid as $r) {
            $r = $r->attributes;
            $this->updateAll(array('is_read' => $status), $this->where(array('senduid' => $r['senduid'], 'senduid' => array('NEQ', $userid), 'recuid' => $r['recuid'], 'msgid' => $r['msgid'], 'is_read' => 0)));
        }
        return true;
    }

    /**
     * 发送私信
     * @param type $userid 发送者UID
     * @param type $data 私信数据
     * @return boolean
     */
    public function msgAdd($userid, $data) {
        if (empty($userid)) {
            $this->addError('', '发送人UID不能为空！');
            return false;
        }
        if (empty($data)) {
            $this->addError('', '数据不能为空！');
            return false;
        }
        //获取发送者会员信息
        $userInfo = MembersModel::model()->getUserInfo((int) $userid);
        //获取接收者会员信息
        $recUserInfo = MembersModel::model()->getUserInfo((int) $data['recuid']);
        if (empty($userInfo) || empty($recUserInfo)) {
            $this->addError('', '该用户不存在！');
            return false;
        }
        //补充标题
        if (empty($data['title'])) {
            $data['title'] = $userInfo['username'] . '给你发送了一条短信息';
        }
        //msg关系表数据
        $msgData = array(
            'senduid' => $userInfo['uid'],
            'suid' => $userInfo['uid'],
            'sendname' => $userInfo['username'],
            'recuid' => $recUserInfo['uid'],
            'ruid' => $recUserInfo['uid'],
            'recuname' => $recUserInfo['username'],
            'userid' => $data['recuid'],
        );
        //检查发者和收着是否已经有同一个回话
        $isAnswer = $this->find($this->where(array(
                    'suid' => $msgData['suid'],
                    'ruid' => $msgData['ruid'],
                    'order' => 'id asc',
        )));
        if (!empty($isAnswer)) {
            $msgData['answerid'] = $isAnswer->id;
        }
        //短信内容数据
        $msgText = MembersMsgTextModel::model();
        $msgText->attributes = $data;
        $msgText->setIsNewRecord(true);
        if (!$msgText->validate()) {
            $this->addErrors($msgText->getErrors());
            return false;
        }
        //短信主体关系
        $this->setIsNewRecord(true);
        $this->attributes = $msgData;
        if ($this->validate()) {
            //添加短信主体关系
            if ($this->save()) {
                $id = $this->primaryKey;
                //更新时间
                if (!empty($isAnswer)) {
                    $this->updateByPk($isAnswer->id, array('datetime' => time()));
                }
                //添加短信内容
                if ($msgText->save()) {
                    $mid = $msgText->primaryKey;
                    //进行短信主题和短信内容关联
                    if ($this->updateByPk($id, array('msgid' => $mid))) {
                        //添加一份到发送者自己的短信主体关系
                        $msgMyData = $msgData;
                        $msgMyData['userid'] = $userid;
                        $msgMyData['msgid'] = $mid;
                        $msgMyData['answerid'] = 0;
                        $msgMyData['suid'] = $msgData['recuid'];
                        $msgMyData['ruid'] = $msgData['senduid'];
                        $msgMyData['is_read'] = 0; //设置未读状态
                        //检查发者和收着是否已经有同一个回话
                        $isAnswer = $this->find($this->where(array(
                                    'suid' => $msgMyData['suid'],
                                    'ruid' => $msgMyData['ruid'],
                                    'order' => 'id asc',
                        )));
                        if (!empty($isAnswer)) {
                            $msgMyData['answerid'] = $isAnswer->id;
                        }
                        unset($this->id);
                        $this->attributes = $msgMyData;
                        $this->setIsNewRecord(true);
                        if ($this->validate() && $this->save()) {
                            //发送通知
                            $this->sendMsgNotice($userInfo['uid'], $userInfo['username'], $recUserInfo['uid'], $msgData['answerid'] ? $msgData['answerid'] : $id);
                            return $id;
                        }
                    }
                }
                //失败
                $this->deleteByPk($id);
                $msgText->deleteByPk($mid);
                $this->addError('', '发送失败！');
                return false;
            } else {
                $this->addError('', '发送失败！');
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 删除用户的所有短信
     * @param type $userid
     * @return boolean
     */
    public function msgDelAll($userid) {
        if (empty($userid)) {
            return false;
        }
        $msgids = $this->findAll($this->where(array('userid' => $userid)));
        if ($this->where(array('userid' => $userid))->delete()) {
            foreach ($msgids as $r) {
                $this->msgDelById($r->msgid);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除用户短信
     * @param type $userid 用户UID
     * @param type $id 短信ID
     * @return boolean
     */
    public function msgDel($userid, $id = 0) {
        if (empty($userid)) {
            return false;
        }
        if (empty($id)) {
            return $this->msgDelAll($userid);
        }
        $msgid = $this->find($this->where(array('userid' => $userid, 'id' => $id)));
        //执行删除
        if ($this->deleteAll($this->where(array('userid' => $userid, 'id' => $id)))) {
            //删除短信内容
            $this->msgDelById($msgid->msgid);
            //删除其他相关记录
            $msgids = $this->findAll($this->where(array('userid' => $userid, 'answerid' => $id)));
            $this->where(array('userid' => $userid, 'answerid' => $id))->delete();
            foreach ($msgids as $r) {
                $this->msgDelById($r->msgid);
            }
            return true;
        } else {
            $this->error = '删除失败！';
            return false;
        }
    }

    /**
     * 删除短信内容
     * @param type $msgid 短信ID
     * @return boolean
     */
    protected function msgDelById($msgid) {
        if (empty($msgid)) {
            return false;
        }
        $count = $this->count($this->where(array('msgid' => $msgid)));
        if ($count) {
            return false;
        }
        return MembersMsgTextModel::model()->deleteByPk($msgid);
    }

    /**
     * 发送一条通知给接收私信的用户
     * @param type $uid 发送者uid
     * @param type $username 发送者用户名
     * @param type $byuid 接收私信的用户uid
     * @param type $msgid 私信ID
     * @return type
     */
    public function sendMsgNotice($uid, $username, $byuid, $msgid) {
        $extendParams = array(
            'uid' => $uid, //谁操作的
            'username' => $username,
            'title' => $username . '给您发了一个私信~',
            'msgid' => $msgid,
        );
        $sendUser = array(
            'uid' => $uid, //谁操作的
            'username' => $username,
        );
        return MessageModel::model()->sendNotice($byuid, $sendUser, MessageModel::sns, $extendParams);
    }

}
